package wxshop.web.user.interception;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import wxshop.api.user.model.User;
import wxshop.api.user.service.UserService;
import wxshop.web.user.dto.FormResult;
import wxshop.web.user.tool.JwtTool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Set;

/**
 * Created by yvdedu.com on 2017/12/30.
 */
@Component
public class CheckLoginHandlerInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private JwtTool jwtTool;

	@Autowired
	private UserService userService;

	@Override
	public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		System.out.println("--------------------------");
		try {
			String token = request.getHeader("token");
			System.out.println("拦截器token----------------"+token);
			if ( token==null ) {
				throw new Exception("请登录后访问");
			}

			User user = jwtTool.toUser(token);//解析出来的user
			System.out.println("拦截器user"+user);

//			HttpSession session = request.getSession();
//			session.setAttribute("id",user.getId());

			HandlerMethod handlerMethod = (HandlerMethod) handler;
			String url = handlerMethod.getBeanType().getSimpleName().replaceFirst("Controller$","");
			url = "/"+url+"/"+handlerMethod.getMethod().getName();
			url = url.toLowerCase();/*全部转为小写*/


			System.out.println(request.getServletPath()+"用户私自访问路径"+url);

			Set<String> userUrls = userService.getUserUrls(user.getId());
			System.out.println("可以访问的路径---"+userUrls);
			System.out.println(request.getServletPath().toLowerCase());
			System.out.println("qweqweqwewqe"+!userUrls.contains(request.getServletPath().toLowerCase()));
			if ( !userUrls.contains(request.getServletPath().toLowerCase()) ) {
				throw new Exception("你不具备访问条件");
			}

			Object controller = ((HandlerMethod) handler).getBean();//访问的controller
			System.out.println(controller);
//			if ( controller instanceof UserAware ) {//判断访问的controller是不是这个接口UserAware的实例
//				((UserAware) controller).setUser(user);//就可以把user给他
//			}


			return true;
		} catch (Exception e) {
			String message = e.getMessage();

			if ( e instanceof UnsupportedJwtException || e instanceof MalformedJwtException || e instanceof SignatureException || e instanceof IllegalArgumentException ) {
				message = "token校验错误";
			} else if ( e instanceof ExpiredJwtException) {
				message = "登录超时";
			}

			response.setStatus(401);
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().println(objectMapper.writeValueAsString(new FormResult(message)));
			return false;
		}
	}
}














